const app = getApp()

Page({
  data: {
    userInfo: {},
    hasUserInfo: false,
    canIUseGetUserProfile: false,
    orderCount: {
      unpaid: 0,
      undelivered: 0,
      delivered: 0,
      completed: 0,
      refund: 0
    },
    favoriteCount: 0,
    addressCount: 0,
    couponCount: 0
  },

  onLoad() {
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }
    
    // 检查用户是否已登录
    this.checkLoginStatus()
  },

  onShow() {
    // 如果已登录，则更新页面数据
    if (this.data.hasUserInfo) {
      this.loadUserData()
    }
  },

  // 检查登录状态
  checkLoginStatus() {
    const userInfo = wx.getStorageSync('userInfo')
    if (userInfo) {
      app.globalData.userInfo = userInfo
      this.setData({
        userInfo,
        hasUserInfo: true
      })
      this.loadUserData()
    }
  },

  // 获取用户信息
  getUserProfile() {
    wx.getUserProfile({
      desc: '用于完善会员资料',
      success: (res) => {
        const userInfo = res.userInfo
        
        // 调用登录接口
        wx.login({
          success: (loginRes) => {
            const code = loginRes.code
            
            // 发送登录请求
            wx.request({
              url: `${app.globalData.apiBaseUrl}/api/user/login`,
              method: 'POST',
              data: {
                code,
                userInfo
              },
              success: (loginResult) => {
                if (loginResult.statusCode === 200 && loginResult.data.code === 200) {
                  // 登录成功
                  const userData = loginResult.data.data
                  
                  // 保存用户信息
                  app.globalData.userInfo = userData
                  wx.setStorageSync('userInfo', userData)
                  
                  this.setData({
                    userInfo: userData,
                    hasUserInfo: true
                  })
                  
                  this.loadUserData()
                } else {
                  wx.showToast({
                    title: '登录失败',
                    icon: 'none'
                  })
                }
              },
              fail: () => {
                wx.showToast({
                  title: '网络错误',
                  icon: 'none'
                })
              }
            })
          }
        })
      }
    })
  },

  // 加载用户数据
  loadUserData() {
    // 获取订单数量
    this.getOrderCount()
    
    // 获取收藏数量
    this.getFavoriteCount()
    
    // 获取地址数量
    this.getAddressCount()
    
    // 获取优惠券数量
    this.getCouponCount()
  },

  // 获取订单数量
  getOrderCount() {
    wx.request({
      url: `${app.globalData.apiBaseUrl}/api/orders/count`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${this.data.userInfo.token}`
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === 200) {
          this.setData({
            orderCount: res.data.data
          })
        }
      }
    })
  },

  // 获取收藏数量
  getFavoriteCount() {
    wx.request({
      url: `${app.globalData.apiBaseUrl}/api/favorites/count`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${this.data.userInfo.token}`
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === 200) {
          this.setData({
            favoriteCount: res.data.data
          })
        }
      }
    })
  },

  // 获取地址数量
  getAddressCount() {
    wx.request({
      url: `${app.globalData.apiBaseUrl}/api/addresses/count`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${this.data.userInfo.token}`
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === 200) {
          this.setData({
            addressCount: res.data.data
          })
        }
      }
    })
  },

  // 获取优惠券数量
  getCouponCount() {
    wx.request({
      url: `${app.globalData.apiBaseUrl}/api/coupons/user/count`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${this.data.userInfo.token}`
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === 200) {
          this.setData({
            couponCount: res.data.data
          })
        }
      }
    })
  },

  // 跳转到订单列表
  goToOrderList(e) {
    const { status } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/order/list?status=${status}`
    })
  },

  // 跳转到地址管理
  goToAddress() {
    wx.navigateTo({
      url: '/pages/address/list'
    })
  },

  // 跳转到我的收藏
  goToFavorites() {
    wx.navigateTo({
      url: '/pages/favorites/index'
    })
  },

  // 跳转到优惠券列表
  goToCoupons() {
    wx.navigateTo({
      url: '/pages/coupon/list'
    })
  },

  // 跳转到个人信息编辑
  goToUserInfo() {
    wx.navigateTo({
      url: '/pages/user/info'
    })
  },

  // 客服
  contactService() {
    // 使用微信提供的客服功能
  },

  // 帮助中心
  goToHelp() {
    wx.navigateTo({
      url: '/pages/help/index'
    })
  },

  // 设置
  goToSettings() {
    wx.navigateTo({
      url: '/pages/settings/index'
    })
  },

  // 注销登录
  logout() {
    wx.showModal({
      title: '提示',
      content: '确定退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          // 清除本地存储
          wx.removeStorageSync('userInfo')
          app.globalData.userInfo = null
          
          this.setData({
            userInfo: {},
            hasUserInfo: false,
            orderCount: {
              unpaid: 0,
              undelivered: 0,
              delivered: 0,
              completed: 0,
              refund: 0
            },
            favoriteCount: 0,
            addressCount: 0,
            couponCount: 0
          })
        }
      }
    })
  }
}) 